package com.crazypos.security.handler;

import com.crazypos.common.ApiRestResponse;
import com.crazypos.common.SecurityResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 * Spring Security登录失败处理类
 */
@Slf4j
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        // 对不同的异常进行不同的处理
        if(e instanceof UsernameNotFoundException){
            log.info("【登录失败】" + e.getMessage());
            SecurityResponse.reponseJson(
                    httpServletResponse,
                    ApiRestResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "用户名不存在")
            );
        }

        if(e instanceof BadCredentialsException){
            log.info("【登录失败】" + e.getMessage());
            SecurityResponse.reponseJson(
                    httpServletResponse,
                    ApiRestResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "用户名或密码不正确")
            );
        }

        log.info("【登录失败】" + e.getMessage());
        SecurityResponse.reponseJson(
                httpServletResponse,
                ApiRestResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "登录失败")
        );
    }
}
